import { defineEventHandler, getQuery } from 'h3';

interface VehicleCostData {
  licensePlate: string;
  totalMileage: number;
  maintenanceCount: number;
  maintenanceCost: number;
  estimatedFuelCost: number;
  totalCost: number;
}

interface CostAnalysisResponse {
  totalMaintenanceCost: number;
  totalEstimatedFuelCost: number;
  averageCostPerVehicle: number;
  costDistribution: {
    fuelRatio: number;
    maintenanceRatio: number;
  };
  vehicleCostData: VehicleCostData[];
  totalVehicles: number;
}

// Mock车辆油耗标准数据（符合7位车牌格式）
const fuelStandards = [
  { licensePlate: '京A12345', fuelConsumption: 8.5 }, // L/100km
  { licensePlate: '京B56789', fuelConsumption: 9.2 },
  { licensePlate: '京C90123', fuelConsumption: 7.8 },
  { licensePlate: '京D34567', fuelConsumption: 10.1 },
  { licensePlate: '京E78901', fuelConsumption: 8.9 },
  { licensePlate: '京F12345', fuelConsumption: 9.5 },
  { licensePlate: '京G56789', fuelConsumption: 8.2 },
  { licensePlate: '京H90123', fuelConsumption: 9.8 },
  { licensePlate: '京J34567', fuelConsumption: 8.6 },
  { licensePlate: '京K78901', fuelConsumption: 9 },
];

// Mock维保花费数据（符合7位车牌格式）
const mockMaintenanceData = [
  { licensePlate: '京A12345', cost: 1200, count: 2 },
  { licensePlate: '京B56789', cost: 800, count: 1 },
  { licensePlate: '京C90123', cost: 1500, count: 3 },
  { licensePlate: '京D34567', cost: 2000, count: 2 },
  { licensePlate: '京E78901', cost: 900, count: 1 },
  { licensePlate: '京F12345', cost: 1800, count: 2 },
  { licensePlate: '京G56789', cost: 1100, count: 1 },
  { licensePlate: '京H90123', cost: 1600, count: 2 },
  { licensePlate: '京J34567', cost: 1300, count: 2 },
  { licensePlate: '京K78901', cost: 950, count: 1 },
];

// Mock里程数据（符合7位车牌格式）
const mockMileageData = [
  { licensePlate: '京A12345', mileage: 15_600 },
  { licensePlate: '京B56789', mileage: 14_200 },
  { licensePlate: '京C90123', mileage: 13_800 },
  { licensePlate: '京D34567', mileage: 12_500 },
  { licensePlate: '京E78901', mileage: 11_900 },
  { licensePlate: '京F12345', mileage: 10_800 },
  { licensePlate: '京G56789', mileage: 9600 },
  { licensePlate: '京H90123', mileage: 8900 },
  { licensePlate: '京J34567', mileage: 8200 },
  { licensePlate: '京K78901', mileage: 7500 },
];

// 油价（元/升）
const fuelPrice = 7.5;

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const { startDate, endDate, licensePlate } = query;

    // 日期处理（目前Mock数据不依赖具体日期范围，仅保留参数接口）
    if (startDate && endDate) {
      // 自定义日期范围（预留接口）
    } else {
      // 默认显示本月数据（预留接口）
    }

    // 生成Mock数据
    const generateMockData = (): VehicleCostData[] => {
      const vehicles = [
        '京A12345',
        '京B56789',
        '京C90123',
        '京D34567',
        '京E78901',
        '京F12345',
        '京G56789',
        '京H90123',
        '京J34567',
        '京K78901',
      ];

      return vehicles.map((vehicle) => {
        // 获取油耗标准
        const fuelStandard = fuelStandards.find(
          (f) => f.licensePlate === vehicle,
        );
        const fuelConsumption = fuelStandard?.fuelConsumption || 8.5;

        // 获取里程数据
        const mileageData = mockMileageData.find(
          (m) => m.licensePlate === vehicle,
        );
        const totalMileage =
          mileageData?.mileage || Math.floor(Math.random() * 10_000) + 5000;

        // 获取维保数据
        const maintenanceData = mockMaintenanceData.find(
          (m) => m.licensePlate === vehicle,
        );
        const maintenanceCost =
          maintenanceData?.cost || Math.floor(Math.random() * 2000) + 500;
        const maintenanceCount =
          maintenanceData?.count || Math.floor(Math.random() * 3) + 1;

        // 计算预估燃油费
        const estimatedFuelCost = Math.round(
          (totalMileage / 100) * fuelConsumption * fuelPrice,
        );

        // 计算总成本
        const totalCost = maintenanceCost + estimatedFuelCost;

        return {
          licensePlate: vehicle,
          totalMileage,
          maintenanceCount,
          maintenanceCost,
          estimatedFuelCost,
          totalCost,
        };
      });
    };

    let vehicleCostData = generateMockData();

    // 车牌号模糊搜索
    if (licensePlate && typeof licensePlate === 'string') {
      vehicleCostData = vehicleCostData.filter((data) =>
        data.licensePlate.toLowerCase().includes(licensePlate.toLowerCase()),
      );
    }

    // 计算汇总数据
    const totalMaintenanceCost = vehicleCostData.reduce(
      (sum, data) => sum + data.maintenanceCost,
      0,
    );
    const totalEstimatedFuelCost = vehicleCostData.reduce(
      (sum, data) => sum + data.estimatedFuelCost,
      0,
    );
    const totalVehicles = vehicleCostData.length;
    const averageCostPerVehicle =
      totalVehicles > 0
        ? Math.round(
            ((totalMaintenanceCost + totalEstimatedFuelCost) / totalVehicles) *
              10,
          ) / 10
        : 0;

    // 计算成本分布
    const totalCost = totalMaintenanceCost + totalEstimatedFuelCost;
    const costDistribution = {
      maintenanceRatio:
        totalCost > 0
          ? Math.round((totalMaintenanceCost / totalCost) * 100)
          : 0,
      fuelRatio:
        totalCost > 0
          ? Math.round((totalEstimatedFuelCost / totalCost) * 100)
          : 0,
    };

    const response: CostAnalysisResponse = {
      totalMaintenanceCost,
      totalEstimatedFuelCost,
      averageCostPerVehicle,
      costDistribution,
      vehicleCostData,
      totalVehicles,
    };

    return {
      success: true,
      data: response,
      message: '获取成功',
    };
  } catch (error) {
    console.error('获取车辆成本分析数据失败:', error);
    return {
      success: false,
      data: null,
      message: '获取数据失败',
    };
  }
});
